package com.gitee.fsmxm.thinking.in.spring.ioc.overview.dependency.lookup;

import com.gitee.fsmxm.thinking.in.spring.ioc.overview.annotation.Super;
import com.gitee.fsmxm.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Map;

/**
 * 依赖查找demo
 * 实时查找
 * 延迟查找
 * 1. 通过名称的方式查找
 * 2. 通过类型的方式查找
 * 3. 通过注解的方式查找
 */
public class DependencyLookupDemo {

    public static void main(String[] args) {

        // 启动spring 上下文
        // 或者  classpath:/META-INF/...
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("META-INF/dependency-lookup-context.xml");

        // 根据名称 实时查找
        lookupInRealtime(beanFactory);
        // 根据名称 延迟查找
        lookupInLazy(beanFactory);
        // 根据类型 实时查找
        lookupByType(beanFactory);
        // 根据类型 实时查找 对象的集合
        lookupWithCollectionsByType(beanFactory);
        // 根据注解 实时查找 对象的集合
        lookupWithCollectionsByAnnotationType(beanFactory);

    }

    private static void lookupWithCollectionsByAnnotationType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, Object> beansOfType = listableBeanFactory.getBeansWithAnnotation(Super.class);
            System.out.println("查找所有@Super标注的类对象: " + beansOfType);
        }
    }

    private static void lookupWithCollectionsByType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> beansOfType = listableBeanFactory.getBeansOfType(User.class);
            System.out.println("查找所有User类对象: " + beansOfType);
        }
    }

    static void lookupByType(BeanFactory beanFactory) {
        User bean = beanFactory.getBean(User.class);
        System.out.println("实时查找: " + bean);
    }

    static void lookupInRealtime(BeanFactory beanFactory) {
        Object user = beanFactory.getBean("user");

        User user1 = (User) user;

        System.out.println("实时查找: " + user1);
    }

    static void lookupInLazy(BeanFactory beanFactory) {
        ObjectFactory<User> objectFactory = (ObjectFactory<User>) beanFactory.getBean("objectFactory");
        User user1 = objectFactory.getObject();
        System.out.println("延迟查找: " + user1);
        System.out.println("----- " + (user1 == beanFactory.getBean("user")));
    }

}
